<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级成绩管理系统 - 三科成绩统计</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .container {
            max-width: 1200px;
            margin-top: 20px;
        }
        .card {
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
            border: none;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            white-space: nowrap;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
        }
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 15px;
        }
        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #667eea;
        }
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .input-group-sm .form-control {
            min-width: 80px;
        }
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .subject-header {
            background-color: #e3f2fd !important;
            font-weight: bold;
        }
        .import-area {
            min-height: 100px;
            font-family: monospace;
        }
        .file-drop-zone {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-drop-zone:hover {
            border-color: #667eea;
            background-color: #f8f9fa;
        }
        .file-drop-zone.dragover {
            border-color: #667eea;
            background-color: #e3f2fd;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="card-header text-center">
                <h3 class="mb-0">
                    <i class="fas fa-graduation-cap me-2"></i>
                    班级成绩管理系统 - 三科成绩统计
                </h3>
                <small>支持53位同学的语文、数学、英语成绩管理</small>
            </div>
            <div class="card-body">
                <!-- 操作按钮区域 -->
                <div class="row mb-3">
                    <div class="col-md-8">
                        <button class="btn btn-success" onclick="generateTemplate()">
                            <i class="fas fa-user-plus me-1"></i>生成53位同学模板
                        </button>
                        <button class="btn btn-info ms-2" data-bs-toggle="modal" data-bs-target="#importModal">
                            <i class="fas fa-upload me-1"></i>批量导入名单
                        </button>
                    </div>
                    <div class="col-md-4 text-end">
                        <button class="btn btn-outline-danger" onclick="clearAllData()">
                            <i class="fas fa-trash me-1"></i>清空所有数据
                        </button>
                        <button class="btn btn-primary ms-2" onclick="calculateAllStats()">
                            <i class="fas fa-calculator me-1"></i>计算统计结果
                        </button>
                    </div>
                </div>

                <!-- 批量导入模态框 -->
                <div class="modal fade" id="importModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="fas fa-upload me-1"></i>
                                    批量导入学生名单
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6><i class="fas fa-keyboard me-1"></i>方式一：文本粘贴</h6>
                                        <p class="text-muted small">每行一个学生姓名，支持53个以内</p>
                                        <textarea class="form-control import-area" id="nameTextArea" 
                                                  placeholder="张三&#10;李四&#10;王五&#10;..." rows="10"></textarea>
                                    </div>
                                    <div class="col-md-6">
                                        <h6><i class="fas fa-file-upload me-1"></i>方式二：文件上传</h6>
                                        <p class="text-muted small">支持.txt或.csv文件，每行一个学生姓名</p>
                                        <div class="file-drop-zone" id="fileDropZone">
                                            <i class="fas fa-cloud-upload-alt fa-2x mb-2"></i>
                                            <p>拖拽文件到此处或点击选择</p>
                                            <input type="file" id="fileInput" accept=".txt,.csv" style="display: none;">
                                        </div>
                                        <div id="fileInfo" style="display: none;">
                                            <small class="text-success">
                                                <i class="fas fa-check-circle me-1"></i>
                                                <span id="fileName"></span> - <span id="studentCount"></span>个学生
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-3">
                                    <h6><i class="fas fa-lightbulb me-1"></i>使用提示：</h6>
                                    <ul class="small text-muted mb-0">
                                        <li>可以粘贴从Excel复制的姓名列表</li>
                                        <li>支持中文姓名，姓名之间用换行分隔</li>
                                        <li>如果名单不足53人，剩余将用"同学X"补齐</li>
                                        <li>如果名单超过53人，将只取前53个</li>
                                    </ul>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" onclick="importNames()">
                                    <i class="fas fa-check me-1"></i>确认导入
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 统计结果区域 -->
                <div id="statsResults" style="display: none;" class="mb-4">
                    <h5 class="text-center mb-3">
                        <i class="fas fa-chart-bar me-1"></i>
                        三科成绩统计结果
                    </h5>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="stat-card">
                                <h6 class="text-primary">语文</h6>
                                <div class="row">
                                    <div class="col-4">
                                        <div class="stat-value text-success" id="chineseMax">-</div>
                                        <div class="stat-label">最高分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-danger" id="chineseMin">-</div>
                                        <div class="stat-label">最低分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-info" id="chineseAvg">-</div>
                                        <div class="stat-label">平均分</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card">
                                <h6 class="text-primary">数学</h6>
                                <div class="row">
                                    <div class="col-4">
                                        <div class="stat-value text-success" id="mathMax">-</div>
                                        <div class="stat-label">最高分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-danger" id="mathMin">-</div>
                                        <div class="stat-label">最低分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-info" id="mathAvg">-</div>
                                        <div class="stat-label">平均分</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card">
                                <h6 class="text-primary">英语</h6>
                                <div class="row">
                                    <div class="col-4">
                                        <div class="stat-value text-success" id="englishMax">-</div>
                                        <div class="stat-label">最高分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-danger" id="englishMin">-</div>
                                        <div class="stat-label">最低分</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-value text-info" id="englishAvg">-</div>
                                        <div class="stat-label">平均分</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 成绩录入表格 -->
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="scoresTable">
                        <thead class="table-light">
                            <tr>
                                <th width="50">序号</th>
                                <th width="150">姓名</th>
                                <th class="subject-header text-center" colspan="3">语文</th>
                                <th class="subject-header text-center" colspan="3">数学</th>
                                <th class="subject-header text-center" colspan="3">英语</th>
                            </tr>
                            <tr>
                                <th></th>
                                <th></th>
                                <th width="80" class="text-center">成绩</th>
                                <th width="80" class="text-center">等级</th>
                                <th width="100" class="text-center">备注</th>
                                <th width="80" class="text-center">成绩</th>
                                <th width="80" class="text-center">等级</th>
                                <th width="100" class="text-center">备注</th>
                                <th width="80" class="text-center">成绩</th>
                                <th width="80" class="text-center">等级</th>
                                <th width="100" class="text-center">备注</th>
                            </tr>
                        </thead>
                        <tbody id="scoresTableBody">
                            <tr>
                                <td colspan="11" class="text-center text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    点击"生成53位同学模板"或"批量导入名单"开始录入成绩
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        let students = [];

        // 生成53位同学模板
        function generateTemplate() {
            if (students.length > 0 && !confirm('已有数据将被覆盖，确定继续吗？')) {
                return;
            }

            students = [];
            for (let i = 1; i <= 53; i++) {
                students.push({
                    id: i,
                    name: `同学${i}`,
                    chinese: { score: '', grade: '', note: '' },
                    math: { score: '', grade: '', note: '' },
                    english: { score: '', grade: '', note: '' }
                });
            }
            renderTable();
        }

        // 批量导入学生名单
        function importNames() {
            const textarea = document.getElementById('nameTextArea');
            const names = textarea.value.trim().split('\n')
                .map(name => name.trim())
                .filter(name => name.length > 0);

            if (names.length === 0 && !document.getElementById('fileName').textContent) {
                alert('请输入学生姓名或选择文件！');
                return;
            }

            let finalNames = names;
            if (finalNames.length === 0) {
                // 从文件读取
                const fileInput = document.getElementById('fileInput');
                if (fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const content = e.target.result;
                        finalNames = content.split('\n')
                            .map(name => name.trim())
                            .filter(name => name.length > 0);
                        processImport(finalNames);
                    };
                    reader.readAsText(file);
                    return;
                }
            }

            processImport(finalNames);
        }

        // 处理导入
        function processImport(names) {
            // 限制最多53个学生
            names = names.slice(0, 53);
            
            // 不足53个用"同学X"补齐
            while (names.length < 53) {
                names.push(`同学${names.length + 1}`);
            }

            students = [];
            names.forEach((name, index) => {
                students.push({
                    id: index + 1,
                    name: name,
                    chinese: { score: '', grade: '', note: '' },
                    math: { score: '', grade: '', note: '' },
                    english: { score: '', grade: '', note: '', }
                });
            });

            renderTable();
            document.getElementById('importModal').querySelector('.btn-close').click();
            
            // 清空导入区域
            document.getElementById('nameTextArea').value = '';
            document.getElementById('fileInput').value = '';
            document.getElementById('fileInfo').style.display = 'none';
            
            alert(`成功导入${students.length}位学生名单！`);
        }

        // 文件拖放功能
        const fileDropZone = document.getElementById('fileDropZone');
        const fileInput = document.getElementById('fileInput');

        fileDropZone.addEventListener('click', () => fileInput.click());
        
        fileDropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileDropZone.classList.add('dragover');
        });

        fileDropZone.addEventListener('dragleave', () => {
            fileDropZone.classList.remove('dragover');
        });

        fileDropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            fileDropZone.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFile(e.target.files[0]);
            }
        });

        function handleFile(file) {
            if (!file.name.endsWith('.txt') && !file.name.endsWith('.csv')) {
                alert('请上传.txt或.csv文件！');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const content = e.target.result;
                const names = content.split('\n')
                    .map(name => name.trim())
                    .filter(name => name.length > 0);
                
                document.getElementById('fileName').textContent = file.name;
                document.getElementById('studentCount').textContent = `${Math.min(names.length, 53)}个学生`;
                document.getElementById('fileInfo').style.display = 'block';
                
                // 自动填充到文本区域
                document.getElementById('nameTextArea').value = names.slice(0, 53).join('\n');
            };
            reader.readAsText(file);
        }

        // 渲染表格
        function renderTable() {
            const tbody = document.getElementById('scoresTableBody');
            tbody.innerHTML = '';

            students.forEach(student => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="text-center">${student.id}</td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${student.name}" 
                               onchange="updateStudentName(${student.id - 1}, this.value)"
                               placeholder="输入姓名">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" min="0" max="100" step="0.1"
                               value="${student.chinese.score}" 
                               onchange="updateScore(${student.id - 1}, 'chinese', 'score', this.value)">
                    </td>
                    <td class="text-center">
                        <span class="badge ${getGradeBadge(student.chinese.score)}">${getGrade(student.chinese.score)}</span>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${student.chinese.note}" 
                               onchange="updateScore(${student.id - 1}, 'chinese', 'note', this.value)"
                               placeholder="备注">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" min="0" max="100" step="0.1"
                               value="${student.math.score}" 
                               onchange="updateScore(${student.id - 1}, 'math', 'score', this.value)">
                    </td>
                    <td class="text-center">
                        <span class="badge ${getGradeBadge(student.math.score)}">${getGrade(student.math.score)}</span>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${student.math.note}" 
                               onchange="updateScore(${student.id - 1}, 'math', 'note', this.value)"
                               placeholder="备注">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" min="0" max="100" step="0.1"
                               value="${student.english.score}" 
                               onchange="updateScore(${student.id - 1}, 'english', 'score', this.value)">
                    </td>
                    <td class="text-center">
                        <span class="badge ${getGradeBadge(student.english.score)}">${getGrade(student.english.score)}</span>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${student.english.note}" 
                               onchange="updateScore(${student.id - 1}, 'english', 'note', this.value)"
                               placeholder="备注">
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 更新学生姓名
        function updateStudentName(index, name) {
            students[index].name = name;
        }

        // 更新成绩
        function updateScore(studentIndex, subject, field, value) {
            if (field === 'score' && value !== '') {
                value = parseFloat(value);
                if (isNaN(value) || value < 0 || value > 100) {
                    alert('请输入0-100之间的有效成绩！');
                    return;
                }
            }
            students[studentIndex][subject][field] = value;
            
            // 更新等级
            if (field === 'score') {
                students[studentIndex][subject].grade = getGrade(value);
                renderTable();
            }
        }

        // 获取等级
        function getGrade(score) {
            if (score === '' || score === null) return '';
            score = parseFloat(score);
            if (score >= 90) return '优秀';
            if (score >= 80) return '良好';
            if (score >= 70) return '中等';
            if (score >= 60) return '及格';
            return '不及格';
        }

        // 获取等级徽章样式
        function getGradeBadge(score) {
            if (score === '' || score === null) return 'bg-secondary';
            score = parseFloat(score);
            if (score >= 90) return 'bg-success';
            if (score >= 80) return 'bg-primary';
            if (score >= 70) return 'bg-info';
            if (score >= 60) return 'bg-warning';
            return 'bg-danger';
        }

        // 计算所有统计结果
        function calculateAllStats() {
            const subjects = ['chinese', 'math', 'english'];
            let hasData = false;

            subjects.forEach(subject => {
                const scores = students
                    .map(s => parseFloat(s[subject].score))
                    .filter(s => !isNaN(s));

                if (scores.length > 0) {
                    hasData = true;
                    const max = Math.max(...scores);
                    const min = Math.min(...scores);
                    const avg = (scores.reduce((sum, score) => sum + score, 0) / scores.length).toFixed(1);

                    document.getElementById(`${subject}Max`).textContent = max;
                    document.getElementById(`${subject}Min`).textContent = min;
                    document.getElementById(`${subject}Avg`).textContent = avg;
                } else {
                    document.getElementById(`${subject}Max`).textContent = '-';
                    document.getElementById(`${subject}Min`).textContent = '-';
                    document.getElementById(`${subject}Avg`).textContent = '-';
                }
            });

            if (hasData) {
                document.getElementById('statsResults').style.display = 'block';
            } else {
                alert('请先录入成绩再计算统计结果！');
            }
        }

        // 清空所有数据
        function clearAllData() {
            if (students.length === 0 || confirm('确定要清空所有数据吗？此操作不可恢复！')) {
                students = [];
                document.getElementById('scoresTableBody').innerHTML = `
                    <tr>
                        <td colspan="11" class="text-center text-muted">
                            <i class="fas fa-info-circle me-1"></i>
                            点击"生成53位同学模板"或"批量导入名单"开始录入成绩
                        </td>
                    </tr>
                `;
                document.getElementById('statsResults').style.display = 'none';
            }
        }

        // 导出数据
        function exportData() {
            if (students.length === 0) {
                alert('暂无数据可导出！');
                return;
            }

            const data = students.map(s => ({
                序号: s.id,
                姓名: s.name,
                语文: s.chinese.score || '',
                数学: s.math.score || '',
                英语: s.english.score || ''
            }));

            const csv = [
                ['序号', '姓名', '语文', '数学', '英语'],
                ...data.map(row => [row.序号, row.姓名, row.语文, row.数学, row.英语])
            ].map(row => row.join(',')).join('\n');

            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `班级成绩_${new Date().toLocaleDateString()}.csv`;
            link.click();
        }
    </script>
</body>
</html>
